<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>万东影院 | 管理员</title>
  <link th:href="@{/images/logo.svg}" rel="icon" type="image/svg+xml">
  <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
  <link th:href="@{/css/bootstrap-icons.min.css}" rel="stylesheet">
</head>
<body>
<header>
  <ul class="nav nav-tabs m-2">
    <li class="nav-item">
      <a class="nav-link disabled">
        <i class="bi bi-person-circle"></i>
        <span class="ms-1">管理员</span>
      </a>
    </li>
    <li class="nav-item">
      <a class="nav-link active" th:href="@{/admin/users}">
        <i class="bi bi-person-lines-fill"></i>
        <span class="ms-1">用户列表</span>
      </a>
    </li>
    <li class="nav-item">
      <a class="nav-link" th:href="@{/admin/log}">
        <i class="bi bi-journals"></i>
        <span class="ms-1">操作日志</span>
      </a>
    </li>
    <li class="nav-item ms-auto">
      <a class="nav-link" th:href="@{/me}">
        <i class="bi bi-person-gear"></i>
        <span class="ms-1">账号管理</span>
      </a>
    </li>
  </ul>
</header>
<main>
  <!-- 搜索框 -->
  <div class="container-fluid mt-3 mb-3">
    <form class="d-flex gap-3">
      <select class="form-select w-auto" th:value="${search}"
              name="search" aria-label="选择搜索的字段">
        <option value="username">用户名</option>
        <option value="id">用户 ID</option>
        <option value="phoneNumber">手机号</option>
      </select>
      <div class="input-group w-25">
        <input class="form-control" name="keyword" aria-label="搜索关键词"
        placeholder="搜索用户列表" th:value="${keyword}">
        <button type="submit" class="input-group-text">
          <i class="bi bi-search"></i>
        </button>
      </div>
      <a class="btn btn-primary" th:href="@{/admin/users/create}">
        <i class="bi bi-person-add"></i>
        <span class="ms-1">新建用户</span>
      </a>
    </form>
  </div>
  <!-- 用户列表表格 -->
  <div class="container-fluid">
    <table class="table">
      <thead>
      <tr>
        <th>用户 ID</th>
        <th>用户名</th>
        <th>用户类型</th>
        <th>手机号</th>
        <th style="width: 250px">创建时间</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr th:each="user : ${page.getContent()}">
        <td th:text="${user.getId()}"></td>
        <td th:text="${user.getUsername()}"></td>
        <td th:text="${user.getRole().getDisplayName()}"></td>
        <td th:text="${user.getPhoneNumber()}"></td>
        <td th:text="${user.getCreatedAt()}"></td>
        <td style="width: 50px">
          <div class="dropdown">
            <button type="button" class="btn" data-bs-toggle="dropdown">
              <i class="bi bi-list"></i>
            </button>
            <ul class="dropdown-menu">
              <li><a class="btn dropdown-item px-3 py-2"
                  th:href="@{/admin/users/{id}(id=${user.getId()})}">
                <i class="bi bi-box-arrow-up-right"></i><span class="ms-3">查看</span>
              </a></li>
              <li><a class="btn dropdown-item px-3 py-2"
                     th:href="@{/admin/users/{id}/edit(id=${user.getId()})}">
                <i class="bi bi-pencil-square"></i><span class="ms-3">编辑</span>
              </a></li>
              <li><button class="btn dropdown-item px-3 py-2 reset-pwd-modal-btn" type="button"
                          th:data-username="${user.getUsername()}"
                          th:data-uid="${user.getId()}"
                          th:data-role="${user.getRole().getDisplayName()}"
              >
                <i class="bi bi-key"></i><span class="ms-3">重置密码</span>
              </button></li>
              <li><button class="btn dropdown-item px-3 py-2 delete-user-modal-btn" type="button"
                          th:data-username="${user.getUsername()}"
                          th:data-uid="${user.getId()}"
                          th:data-role="${user.getRole().getDisplayName()}"
              >
                <i class="bi bi-trash"></i><span class="ms-3">删除此用户</span>
              </button></li>
            </ul>
          </div>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
  <!-- 页码 -->
  <div class="container-fluid clearfix">
    <div class="float-start">
      <span>共找到 <span th:text="${page.getTotalElements()}"></span> 名用户</span>
    </div>
    <div class="d-flex justify-content-center">
      <ul class="nav">
        <li class="nav-item">
          <a class="nav-link" th:if="${page.getNumber()} > 0"
          th:href="@{/admin/users(page=${page.getNumber()}, search=${search}, keyword=${keyword})}"
          >上一页</a>
          <a class="nav-link disabled" th:if="${page.getNumber()} == 0">上一页</a>
        </li>
        <li class="nav-item">
          <a class="nav-link disabled">
            当前 <span th:text="${page.getNumber() + 1}"></span>页
            / 总共 <span th:text="${page.getTotalPages()}"></span> 页
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link"
             th:if="${page.getNumber()} < ${page.getTotalPages() - 1}"
             th:href="@{/admin/users(page=${page.getNumber() + 2}, search=${search}, keyword=${keyword})}"
          >下一页</a>
          <a class="nav-link disabled"
             th:if="${page.getNumber()} == ${page.getTotalPages() - 1}">下一页</a>
        </li>
      </ul>
    </div>
    <input type="hidden" th:value="${page.getNumber() + 1}" id="currentPage">
  </div>
  <div>
    <!-- 重置密码弹窗 -->
    <div class="modal fade" id="resetPasswordModal" tabindex="-1">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5">确认此操作</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <p>是否重置该用户的密码</p>
            <div class="d-flex flex-column gap-2">
              <div>
                <label class="small mb-1">用户 ID</label>
                <div class="card p-2">
                  <span class="uid-text"></span>
                </div>
              </div>
              <div>
                <label class="small mb-1">用户名</label>
                <div class="card p-2">
                  <span class="username-text"></span>
                </div>
              </div>
              <div>
                <label class="small mb-1">身份</label>
                <div class="card p-2">
                  <span class="role-text"></span>
                </div>
              </div>
            </div>
            <div class="alert alert-danger mt-4">
              <i class="bi bi-exclamation-triangle-fill"></i>
              <span class="ms-2">注意：此操作不可逆</span>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary"
                    id="resetPwdBtn" data-bs-dismiss="modal">确认</button>
          </div>
        </div>
      </div>
    </div>
    <!-- 删除用户弹窗 -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5">确认此操作</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <p>是否删除该用户</p>
            <div class="d-flex flex-column gap-2">
              <div>
                <label class="small mb-1">用户 ID</label>
                <div class="card p-2">
                  <span class="uid-text"></span>
                </div>
              </div>
              <div>
                <label class="small mb-1">用户名</label>
                <div class="card p-2">
                  <span class="username-text"></span>
                </div>
              </div>
              <div>
                <label class="small mb-1">身份</label>
                <div class="card p-2">
                  <span class="role-text"></span>
                </div>
              </div>
            </div>
            <div class="alert alert-danger mt-4">
              <i class="bi bi-exclamation-triangle-fill"></i>
              <span class="ms-2">注意：此操作不可逆</span>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary"
                    id="deleteUserBtn" data-bs-dismiss="modal">确认</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<script th:src="@{/js/axios.min.js}"></script>
<script th:src="@{/js/bootstrap.bundle.min.js}"></script>
<script>
  function showResetPasswordModal(uid, username, role) {
    const modal = document.getElementById("resetPasswordModal");

    modal.querySelector(".uid-text").textContent = uid;
    modal.querySelector(".username-text").textContent = username;
    modal.querySelector(".role-text").textContent = role;

    const bsModal = new bootstrap.Modal(modal);
    bsModal.show();
  }

  function setResetPwdModalButton() {
    const buttons = document.querySelectorAll(".reset-pwd-modal-btn");

    buttons.forEach(button  => {
      const dataset = button.dataset;
      button.addEventListener("click", () => showResetPasswordModal(
          dataset.uid, dataset.username, dataset.role));
    });
  }

  setResetPwdModalButton();

  function showDeleteModal(uid, username, role) {
    const modal = document.getElementById("deleteModal");

    modal.querySelector(".uid-text").textContent = uid;
    modal.querySelector(".username-text").textContent = username;
    modal.querySelector(".role-text").textContent = role;

    const bsModal = new bootstrap.Modal(modal);
    bsModal.show();
  }

  function setDeleteUserModalButton() {
    const buttons = document.querySelectorAll(".delete-user-modal-btn");

    buttons.forEach(button => {
      const dataset = button.dataset;
      button.addEventListener("click", () => showDeleteModal(
          dataset.uid, dataset.username, dataset.role
      ))
    })
  }

  setDeleteUserModalButton();

  async function resetPassword(id) {
    try {
      const response = await axios.post(`/api/users/${id}/password/reset`);
      console.log(response);
      alert("重置密码成功");
      location.reload();
    } catch (error) {
      console.log(error);
    }
  }

  function setResetPwdButton() {
    const button = document.getElementById("resetPwdBtn");
    const modal = document.getElementById("resetPasswordModal");
    button.addEventListener("click", event => {
      event.preventDefault();
      resetPassword(modal.querySelector(".uid-text").textContent);
    });
  }

  setResetPwdButton();

  async function deleteUser(id) {
    try {
      const response = await axios.delete("/api/users/" + id);
      console.log(response);
      alert("删除用户成功");
      location.reload();
    } catch (error) {
      console.log(error);
      if (error.response.status === 409) {
        alert(error.response.data);
      }
    }
  }

  function setDeleteUserButton() {
    const button = document.getElementById("deleteUserBtn");
    const modal = document.getElementById("deleteModal");
    button.addEventListener("click", event => {
      event.preventDefault();
      deleteUser(modal.querySelector(".uid-text").textContent)
    })
  }

  setDeleteUserButton();
</script>
</body>
</html>